<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    :close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="品牌Logo" prop="brandLogo">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="uploadHeaders"
          name="file"
          :show-file-list="false"
          :on-success="handleLogoSuccess"
          :on-error="(err) => ElMessage.error('上传失败: ' + err)"
          :before-upload="beforeLogoUpload"
        >
          <img v-if="form.logo" :src="form.logo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>

      <el-form-item label="是否显示" prop="isShow">
        <el-switch v-model="form.isShow" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handlerConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from "vue";
import { createBrand, updateBrand } from "@/api/brand";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const getToken = () => {
  return localStorage.getItem("token") || "";
};

// 修改上传URL为前端地址
const uploadUrl = `${
  import.meta.env.VITE_UPLOADS_URL
}/api/FileUploadManage/upload`;

const formRef = ref(null);
const form = ref({
  id: "",
  name: "",
  logo: "",
  sort: 1,
  isShow: true,
});

const props = defineProps({
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogTableValue: {
    type: Object,
    default: () => ({}),
  },
  dialogVisible: {
    type: Boolean,
    default: false,
  },
});

watch(
  () => props.dialogTableValue,
  () => {
    form.value = { ...props.dialogTableValue };
  },
  { deep: true, immediate: true }
);

const rules = ref({
  name: [
    {
      required: true,
      message: "请输入品牌名称",
      trigger: "change",
    },
    {
      max: 50,
      message: "品牌名称不能超过50个字符",
      trigger: "change",
    },
  ],
  sort: [
    {
      required: true,
      message: "请输入排序值",
      trigger: "change",
    },
  ],
});

const emits = defineEmits(["update:modelValue", "initGetList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`,
};

const handleLogoSuccess = (response) => {
  if (response.result) {
    // 使用正确的响应格式，filePath 包含了完整的文件路径
    form.value.logo = `${import.meta.env.VITE_UPLOADS_URL}${response.filePath}`;
    ElMessage.success(response.message || "上传成功");
  } else {
    ElMessage.error("上传失败: " + (response.message || "未知错误"));
  }
};

const beforeLogoUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("Logo必须是JPG或PNG格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("Logo图片大小不能超过2MB!");
    return false;
  }
  return true;
};

const handlerConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (props.dialogTitle === "添加品牌") {
          await createBrand(form.value);
        } else {
          await updateBrand(form.value);
        }
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        emits("initGetList");
        handleClose();
      } catch (error) {
        console.error("操作失败:", error);
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
